package service

import (
	"log"
	"net/http"

	"github.com/Kindling-project/chaos-backend/api"
	"github.com/Kindling-project/chaos-backend/internal/manager"
	"github.com/gin-gonic/gin"
)

func RegisterChaos(router *gin.RouterGroup) {
	chaosRouter := router.Group("chaos")
	{
		chaosRouter.GET("/list", ListChaos)
		chaosRouter.POST("/create", CreatChaos)
		chaosRouter.GET("/status", StatusChaos)
		chaosRouter.GET("/stop", DeleteChaos)
	}
}

func ListChaos(c *gin.Context) {
	chaos, err := manager.ListChaos()
	if err != nil {
		log.Printf("failed to list chaos,err: %v\n", err)
		api.Response(c, http.StatusInternalServerError, 500, "failed to list chaos", nil)
		return
	}

	api.ResponseOK(c, "", api.Data{
		"chaos_list": chaos,
	})
}

func CreatChaos(c *gin.Context) {
	chaosVO := api.Chaos{}
	c.BindJSON(&chaosVO)
	chaos, err := manager.CreateChaos(&chaosVO)
	if err != nil {
		log.Printf("failed to create chaos,err: %v\n", err)
		api.Response(c, http.StatusInternalServerError, 500, "failed to create chaos", nil)
		return
	}

	manager.AddNoteAfterInjected(chaos)

	api.ResponseOK(c, "", api.Data{
		"chaos_list": chaos,
	})
}

func DeleteChaos(c *gin.Context) {
	lastChaos, err := manager.DeleteChaos()
	if err != nil {
		log.Printf("failed to delete chaos,err: %v\n", err)
		api.Response(c, http.StatusInternalServerError, 500, "failed to delete chaos", nil)
		return
	}

	api.ResponseOK(c, "", api.Data{
		"chaos": lastChaos,
	})
}

func StatusChaos(c *gin.Context) {
	lastChaos, err := manager.Status()

	manager.AddNoteAfterInjected(lastChaos)

	if err != nil {
		log.Printf("failed to check chaos status,err: %v\n", err)
		api.Response(c, http.StatusInternalServerError, 500, "failed to get chaos status", nil)
		return
	}

	if lastChaos == nil {
		api.ResponseOK(c, "", api.Data{
			"chaos":  nil,
			"status": 0,
		})
		return
	}

	api.ResponseOK(c, "", api.Data{
		"chaos":  lastChaos,
		"status": lastChaos.Status,
	})
}
